import efinance as ef
from utils.statistics import get_result, get_trend_and_continue_days
from utils.ding import send
from datetime import datetime, timedelta
import requests
import json
import time
from typing import Annotated

# from http.client import HTTPConnection
# import logging
# HTTPConnection.debuglevel = 1
# logging.basicConfig()  # 初始化 logging，否则不会看到任何 requests 的输出。
# logging.getLogger().setLevel(logging.DEBUG)
# requests_log = logging.getLogger("requests.packages.urllib3")
# requests_log.setLevel(logging.DEBUG)
# requests_log.propagate = True


def get_fund_yield() -> (Annotated[None | float, "10年期国债收益率"], Annotated[None | float, "30年期国债收益率"]):
    """获取10年、30年国债的收益率"""
    ten_response = requests.get(
        url="https://api-ddc-wscn.awtmt.com/market/real",
        params={
            "fields": "symbol,prod_name,last_px,px_change,px_change_rate,high_px,low_px,open_px,"
                      "update_time,week_52_high,week_52_low",
            "prod_code": "CN10YR.OTC"
        },
        headers={
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/126.0.0.0 Safari/537.36"
        }
    )
    thirty_response = requests.get(
        url="https://hq.sinajs.cn",
        params={
            "rn": int(time.time() * 1000),
            "list": "globalbd_gcny30"
        },
        headers={
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/126.0.0.0 Safari/537.36",
            "Referer": "https://stock.finance.sina.com.cn/forex/globalbd/gcny30.html"
        }
    )
    try:
        ret = json.loads(ten_response.text)
        ret1 = ret["data"]["snapshot"]["CN10YR.OTC"][2]
    except:
        print(f"获取10年期国债收益率失败！")
        ret1 = None
    try:
        # var hq_str_globalbd_gcny30="中国30年期国债收益率,2.4860,2.4790,2.4860,2.5300,2.4760,0,0.0028,0.0070,0.0000,0.0000,1721797526,2024-07-24,13:05:26";
        # 解释：2.4860 表示开盘价， 2.4790表示昨天收盘价， 2.4860表示当前价，2.5300 表示最高， 2.4760 表示最低
        ret2 = float(thirty_response.text.split(',')[3])
    except:
        print(f"获取30年期国债收益率失败！")
        ret2 = None
    return ret1, ret2


def main():
    fund_10_yield, fund_30_yield = get_fund_yield()
    msgs = []
    if fund_30_yield:
        msgs.append(f"【30年期国债】收益率{fund_30_yield}"
                    f"{'高于风险值2.5,建议买长债' if fund_30_yield > 2.5 else '低于风险值2.5,建议买短债'}")
    if fund_10_yield:
        msgs.append(f"【10年期国债】收益率{fund_10_yield}"
                    f"{'高于风险值2.25,建议买长债' if fund_10_yield > 2.25 else '低于风险值2.25,建议买短债'}")

    # 指数
    five_years_ago = (datetime.now() - timedelta(365 * 5)).strftime("%Y%m%d")
    for stock in ['上证50', '沪深300', '中证500', '中证1000', '中证2000', '创业板指', '科创50']:
        # ['股票名称', '股票代码', '日期', '开盘', '收盘', '最高', '最低', '成交量', '成交额', '振幅', '涨跌幅', '涨跌额', '换手率']
        df = ef.stock.get_quote_history(stock, beg=five_years_ago)
        df = df[["日期", "涨跌额", "成交量", "成交额"]]

        continue_result, increased_trading_result = get_result(df)
        r1 = round(increased_trading_result['then_continue_decline_count']*100/increased_trading_result['decline_count'], 2)
        r2 = round(increased_trading_result['then_continue_raise_count'] * 100 / increased_trading_result['raise_count'], 2)
        print(f"【{stock}】放量下跌后继续下跌概率：{r1}, 放量上涨后继续上涨概率：{r2}")

        # 计算明天的涨跌可能性
        is_raise_trend, increased_trading_ratio, continue_days = get_trend_and_continue_days(df)
        msg = f"【{stock}】{'放量' if increased_trading_ratio > 0 else '缩量'}{abs(increased_trading_ratio)}"
        # 放量之后的概率预测
        if is_raise_trend is not None and increased_trading_ratio > 0.2:
            trend = '上涨' if is_raise_trend else '下跌'
            if is_raise_trend and increased_trading_result["raise_count"]:
                predict_probability = round(increased_trading_result["then_continue_raise_count"] * 100 /
                                            increased_trading_result["raise_count"], 2)
                msg += f",预测明天{trend}概率{predict_probability}%({increased_trading_result['raise_count']})"

            elif not is_raise_trend and increased_trading_result["decline_count"]:
                predict_probability = round(increased_trading_result["then_continue_decline_count"] * 100 /
                                            increased_trading_result["decline_count"], 2)
                msg += f",预测明天{trend}概率{predict_probability}%({increased_trading_result['decline_count']})"

        # 连续涨跌后的概率预测
        if continue_days > 1 and is_raise_trend is not None:
            if is_raise_trend:
                item = continue_result[str(continue_days)]
                if item['rise_total_count']:
                    ratio = round(item['rise_decline_count'] * 100 / item['rise_total_count'], 2)
                    if item['recently_rise_total_count']:
                        rec_ratio = round(item['recently_rise_decline_count'] * 100 / item['recently_rise_total_count'],
                                          2)
                        msg += (f"已连续上涨{continue_days}天,"
                                f"明天预测下跌概率{ratio}({item['rise_total_count']}),"
                                f"近期下跌概率{rec_ratio}({item['recently_rise_total_count']})")
                    else:
                        msg += (f"已连续上涨{continue_days}天,"
                                f"明天预测下跌概率{ratio}({item['rise_total_count']})")
                else:
                    msg += f"已连续上涨{continue_days}天,还没有出现过连续上涨这么多天!"

            elif is_raise_trend is False:
                item = continue_result[str(continue_days)]
                if item['decline_total_count']:
                    ratio = round(item['decline_rise_count'] * 100 / item['decline_total_count'], 2)
                    if item['recently_decline_total_count']:
                        rec_ratio = round(
                            item['recently_decline_rise_count'] * 100 / item['recently_decline_total_count'], 2)
                        msg += (f",已连续下跌{continue_days}天,"
                                f"近5年数据明天上涨概率:{ratio},"
                                f"近1年数据明天上涨概率:{rec_ratio}({item['recently_decline_total_count']})")
                    else:
                        msg += f",已连续下跌{continue_days}天,近5年数据明天上涨概率{ratio}({item['decline_total_count']})"
                else:
                    msg += f",已连续下跌{continue_days}天,还没有出现过连续下跌这么多天!"

        if msg:
            msgs.append(msg)

    send('\n'.join(msgs))


if __name__ == '__main__':
    main()
